<?php
// +----------------------------------------------------------------------
// | 办公管理
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use app\admin\model\ChangeModel;
use app\admin\model\ContractModel;
use app\admin\model\PayDepositModel;
use app\admin\model\PayRefundModel;
use app\admin\model\ServiceDepositModel;
use app\admin\model\ArchivesDeceasedModel;
use app\admin\model\TombareaRowColModel;
use app\admin\model\ServiceMoveModel;
use cmf\controller\AdminBaseController;
use app\admin\model\OrderModel;
use app\admin\model\OrderPayLogModel;
use think\Db;

class OfficeController extends AdminBaseController
{
    protected $result_list =0;
    public function initialize()
    {
        $this->user_model = Db::name("user");
        $this->dept_model = Db::name("department");
        $this->notice_model = Db::name("notice");
        $this->notice_user_model = Db::name("noticeUser");
        $this->log_model = Db::name("outinLog");
        parent::initialize();
    }

    public function index()
    {
        $this->assign("results", '');
        return $this->fetch();
    }

    /*人员管理*/
    public function personnel()
    {
        /*搜索条件*/
        $user_nickname = $this->request->param("user_nickname");
        $user_login = $this->request->param("user_login");

        $users['last_login_time'] = time();
        $users = $this->user_model->alias("d")->field("d.*,p.department_name,p.dept_type")->where('user_nickname', 'like', '%' . $user_nickname . '%')
            ->join("dj_department p", "p.id=d.dept_id", "right")
            ->where('user_login', 'like', '%' . $user_login . '%')
            ->where('user_type', 2)
            ->order('d.id', 'DESC')->paginate(15);
        //dump($this->user_model->getLastSql());
        $page = $users->render();

        $this->assign("users", $users);
        $this->assign("page", $page);
        return $this->fetch();
    }

    /*获取部门*/
    public function get_dept()
    {
        $dept = $this->dept_model->where('is_delete', '=', 0)->select();
        $this->assign('dept', $dept);
    }

    /*人员添加--跳转传值*/
    public function add()
    {
        $this->get_dept();
        return $this->fetch();
    }

    /*人员添加--保存*/
    public function addpost()
    {
        $data = $this->request->param();
        $info =  $this->user_model->where(['user_login'=>$data['user_login']])->find();
        if ($info){
            return $this->error('账号重复！');
        }
        $data['entry_time'] = strtotime($data['entry_time']);
        $data['user_pass'] = cmf_password($data['user_pass']);
        $data['user_type'] = 2;
        $this->user_model->insert($data);
        //dump($this->user_model->getLastSql());
        $this->success("添加成功！", url("Office/personnel"));
    }

    /*人员编辑--跳转传值*/
    public function editperson()
    {
        $this->get_dept();
        $id = $this->request->param('id');
        $entry_time = $this->request->param('entry_time');
        $where = array(
            'id' => $id,
        );
        $result = $this->user_model->where($where)->find();

        $this->assign($result);
        $this->assign("users", $result);
        return $this->fetch();
    }

    /*人员编辑--保存*/
    public function editpersonpost()
    {
        $data = $this->request->param();

        $data['entry_time'] = strtotime($data['entry_time']);
        //dump($data);exit;
        $this->user_model->update($data);
        $this->success("保存成功", url("Office/personnel"));
    }

    /*人员管理--变更*/
    public function status()
    {
        $id = $this->request->param("id", 0, 'intval');
        $status = $this->request->param("show", '0');
        $field = $this->request->param("field", 'user_status');

        $saveData = array(
            'id' => $id,
            $field => $status == '0' ? '1' : '0'
        );

        $this->user_model->update($saveData);
        $this->success("修改成功", url("Office/personnel"));
    }


    /*重置密码*/
    public function resetpassword()
    {
        $id = $this->request->param("id");
        $result = $this->user_model->where(array('id' => $id))->find();
        $this->assign($result);
        return $this->fetch();
    }

    /*重置密码*/
    public function resetpasswordpost()
    {
        $data = $this->request->param();
        $data['user_pass'] = cmf_password($data['user_pass']);
        $this->user_model->update($data);

        $this->success('修改成功', url('Office/personnel'));
    }

    /*设置权限*/
    public function permission()
    {
        $content = hook_one('admin_user_edit_view');

        if (!empty($content)) {
            return $content;
        }

        $id = $this->request->param('id', 0, 'intval');
        $roles = DB::name('role')->where('status', 1)->order("id DESC")->select();
        $this->assign("roles", $roles);
        $role_ids = DB::name('RoleUser')->where("user_id", $id)->column("role_id");
        $this->assign("role_ids", $role_ids);

        $user = DB::name('user')->where("id", $id)->find();
        $this->assign($user);
        return $this->fetch();
    }

    /*设置权限--保存*/
    public function permissioneditost()
    {
        if ($this->request->isPost()) {
            if (!empty($_POST['role_id']) && is_array($_POST['role_id'])) {
                if (empty($_POST['user_pass'])) {
                    unset($_POST['user_pass']);
                } else {
                    $_POST['user_pass'] = cmf_password($_POST['user_pass']);
                }
                $role_ids = $this->request->param('role_id/a');
                unset($_POST['role_id']);

                //$_POST['user_type'] = 1;

                $result = DB::name('user')->update($_POST);
                if ($result !== false) {
                    $uid = $this->request->param('id', 0, 'intval');
                    DB::name("RoleUser")->where("user_id", $uid)->delete();
                    foreach ($role_ids as $role_id) {
                        if (cmf_get_current_admin_id() != 1 && $role_id == 1) {
                            $this->error("为了网站的安全，非网站创建者不可创建超级管理员！");
                        }
                        DB::name("RoleUser")->insert(["role_id" => $role_id, "user_id" => $uid]);
                    }
                    $this->success("保存成功！", url('Office/personnel'));
                } else {
                    $this->error("保存失败！");
                }

            } else {
                $this->error("请为此用户指定角色！");
            }

        }
    }

    /**
     * 部门管理
     */
    public function department()
    {
        $this->get_user_nickname();
        $where = array(
            'is_delete' => 0,
        );

        $department_name = $this->request->param("department_name");

        $results = $this->dept_model->alias("p")
            ->field("p.*,u.user_nickname")
            ->join("dj_user u", "p.user_id=u.id", "left")
            ->where($where)
            ->where('department_name', 'like', '%' . $department_name . '%')
            ->order('id', 'DESC')
            ->paginate(15);

        $page = $results->render();
        $this->assign("results", $results);
        $this->assign("page", $page);
        return $this->fetch();
    }

    /*获取用户名*/
    public function get_user_nickname()
    {
        $user = $this->user_model->where(0)->select();
        $this->assign('user', $user);
    }

    /*部门管理--添加页面跳转*/
    public function add_department()
    {
        $this->get_user_nickname();
        return $this->fetch();
    }

    /*部门管理--添加页面保存*/
    public function add_post()
    {
        $data = $this->request->param();
        $data['add_time'] = time();
        $data['add_user'] = cmf_get_current_admin_id();

        $this->dept_model->insert($data);
        $this->success("添加成功！", url("Office/department"));
    }

    /*部门管理--编辑页面跳转*/
    public function edit()
    {
        $this->get_user_nickname();
        $id = $this->request->param("id", 0, '');
        $where = array(
            'id' => $id
        );
        $result = $this->dept_model->where($where)->find();

        $this->assign($result);

        return $this->fetch();
    }

    /*部门管理--编辑页面保存*/
    public function edit_post()
    {
        $data = $this->request->param();
        $this->dept_model->update($data);

        $this->success('保存成功', url('Office/department'));
    }

    /*部门管理--软删除*/
    public function delete()
    {
        $id = $this->request->param("id");
        $status = $this->request->param("is_delete", '0');
        $saveData = array(
            'id' => $id,
            'is_delete' => $status == '0' ? '1' : '0'
        );

        $this->dept_model->update($saveData);
        $this->success("删除成功", url("Office/department"));
    }


    /*通知管理--列表*/
    public function notice()
    {
        //获取添加人
        $data = $this->request->param('user_nickname');

        //查询结果提交
        $results = $this->notice_model->alias('n')->field('n.*,u.user_nickname')
            ->join('dj_user u', 'u.id=n.add_user')
            ->where('user_nickname', 'like', '%' . $data . '%')
            ->order('n.add_time','desc')
            ->paginate(15);

        $page = $results->render();
        $this->assign("results", $results);
        $this->assign("page", $page);
        return $this->fetch();
    }

    /*通知管理--删除*/
    public function notice_delete()
    {
        $data = $this->request->param();
        $notice_id = $this->request->param("id");
        //删除子表
        $this->noticeUserDelete($notice_id);

        $this->notice_model->delete($data);

        $this->success("删除成功", url("Office/notice"));
    }

    /*通知人员关联表noticeUser删除*/
    public function noticeUserDelete($notice_id)
    {
        Db::name("noticeUser")
            ->where('notice_id', $notice_id)
            ->delete();
    }

    /*通知管理--选择人员*/
    public function search_notice()
    {

        $notice_ids = $this->request->param("notice_ids");
        $notice_names = $this->request->param("notice_names");

        $usersList = $this->user_model->alias('u')->field('u.*,p.department_name')
            ->leftjoin('dj_department p', 'p.id=u.dept_id')
            ->where('p.dept_type','<>','5')
            ->where('p.dept_type','<>','7')
            ->where('p.dept_type','<>','8')
            ->order("p.dept_type")
            ->paginate(15);

        $this->assign('usersList', $usersList);
        $page = $usersList->render();
        $this->assign("page", $page);
        $this->assign("notice_ids", explode(",",rtrim($notice_ids, ',')));
        $this->assign("selected_ids", $notice_ids);
        $this->assign("selected_names", $notice_names);
        $this->display();

        return $this->fetch();
    }

    /*通知管理--添加页面*/
    public function noticeadd()
    {
        return $this->fetch();
    }


    /*通知人员关联表*/
    public function addNoticeUser($notice_id)
    {
        /*
         * 获取notice_id user_id
         * */
        $data['notice_id'] = $notice_id;
        $user_id = $_POST['userIdSelect'];

        //strpos:查找数据在字符串中第一次出现的位置返回int
        //判断user_id是否为空
        if (strpos($user_id, ',') != false && $user_id != null) {
            //explode：把字符串拆分为数组
            $struser = explode(',', $user_id);
            //数组按索引循环赋值给user_id
            for ($i = 0; $i < count($struser); $i++) {
                $data['user_id'] = $struser[$i];
                Db::name("noticeUser")->insertGetId($data);
            }
        }
        //echo Db::name("noticeUser")->getLastSql();
    }

    /*通知提交*/
    public function noticeadd_post()
    {
        $data = $this->request->param();
        //获取前台user_id
        $user_id = $_POST['userIdSelect'];
        //判断user_id是否为空或者为null
        if (empty($user_id) || $user_id == null) {
            $this->error("请选择通知人员");
        }

        //前台获取要插入的数据
        $newdata = array('notice_title' => $data['notice_title'],
            'notice_content' => $data['notice_content'],
            'add_time' => time(),
            'add_user' => cmf_get_current_admin_id());

        //插入数据返回id
        $id = $this->notice_model->insertGetId($newdata);
        //判断是否有id
        if ($id != false) {
            $this->addNoticeUser($id);
            $this->success("添加成功", url('Office/notice'));
        } else {
            $this->error("添加失败");
        }
    }

    /*通知查看*/
    public function noticelook()
    {
        $id = $this->request->param("id");

        $results = $this->notice_model->alias('n')
            ->join('dj_notice_user nu', 'nu.notice_id=n.id')
            ->join('dj_user u', 'nu.user_id=u.id')
            ->where('nu.notice_id', '=', $id)
            ->field('u.user_nickname,nu.is_read,nu.read_time')
            ->paginate(15);

        $page = $results->render();
        $this->assign("results", $results);
        $this->assign("page", $page);
        return $this->fetch();
    }

    /*通知列表*/
    public function noticelist()
    {
        $start_time = $this->request->param("start_time");
        $end_time = $this->request->param("end_time");
        if (empty($end_time)) {
            $end_time = 99999999999;
        }
        if (empty($end_time)) {
            $start_time = 0;
        }

        $user_id = cmf_get_current_admin_id();
        //dump($data);exit;
        //查询结果提交
        $results = $this->notice_model->alias('n')->field('n.*,u.user_nickname,nu.is_read')
            ->join('dj_notice_user nu', 'nu.notice_id=n.id')
            ->join('dj_user u', 'u.id=n.add_user')
            ->whereTime('n.add_time', '>=', $start_time)
            ->whereTime('add_time', '<=', $end_time)
            //->whereTime('n.add_time',[$start_time, $end_time])
            ->where('nu.user_id', '=', $user_id)
            ->order('nu.is_read', 'asc')
            ->order('n.add_time', 'desc')
            ->paginate(15);

        //echo Db::name('notice')->getLastSql();
        $page = $results->render();
        $this->assign("results", $results);
        $this->assign("page", $page);
        return $this->fetch();
    }

    /*通知列表查看*/
    public function noticelistlook()
    {
        $id = $this->request->param("id");
        if ($id != false) {
            $this->noticeListAdd($id);
        }

        $result = $this->notice_model->alias('n')
            ->join('dj_user u', 'u.id=n.add_user')
            ->where('n.id', $id)
            ->find();

        $this->assign($result);
        return $this->fetch();
    }

    /*更新状态和时间*/
    public function noticeListAdd($notice_id)
    {
        $user_id = cmf_get_current_admin_id();
        $this->notice_user_model->alias('nu')
            ->where('notice_id', '=', $notice_id)
            ->where('nu.user_id', '=', $user_id)
            ->join('dj_notice n', 'n.id=nu.notice_id')
            ->join('dj_user u', 'u.id=nu.user_id')
            ->update(
                [
                    'read_time' => time(),
                    'is_read' => "T"
                ]
            );
    }

    /*通知人员关联表noticeUser删除*/
    public function noticelist_delete()
    {
        $notice_id = $this->request->param("id");
        $user_id = cmf_get_current_admin_id();

        Db::name("noticeUser")
            ->where('notice_id', $notice_id)
            ->where('user_id', $user_id)
            ->delete();

        $this->success("删除成功", url('Office/noticelist'));
    }


    /*审批管理*/
    public function approval()
    {
        $model = Db::name("approval");

        $apply_user = $this->request->param("apply_user");
        $form_type = $this->request->param("form_type");
        $approval_status = $this->request->param("approval_status");
        if (!empty($form_type)){
            $model->where('a.form_type',$form_type);
        }
        if (!empty($approval_status)){
            $model->where('a.approval_status',$approval_status);
        }
        if (!empty($form_type)){
            $model->where("u1.user_nickname","like","%$apply_user%");
        }
        $results = $model->alias("a")->field("a.*,a.id aid,u1.user_nickname apply_name,u2.user_nickname approval_name")
            ->leftJoin("user u1", "u1.id=a.apply_user" )
            ->leftJoin("user u2", "u2.id=a.approval_user" )
            ->order("a.apply_time desc")
            ->paginate(10);
//var_dump($model->getLastSql());
        $page = $results->render();
        $this->assign("results", $results);

        $this->assign("form_type", $form_type);
        $this->assign("approval_status", $approval_status);

        $this->assign("page", $page);

        return $this->fetch();
    }

    /*审批管理-去审批*/
    public function approvaladd()
    {
        $id = $this->request->param('id');
        $app_status =  $this->request->param('app_status');
        $result = Db::name("approval")->alias("a")->field('a.*,u.user_nickname')
            ->leftJoin("user u", "u.id=a.apply_user")
            ->where('a.id', $id)
            ->find();
        $result['apply_time'] = date('Y/m/d H:i:s',$result['apply_time']);


        $this->assign($result);
        $this->assign('approval_id',$result['id']);

        $this->assign("show_flag", "2"); // 2的时候不显示
        $this->assign("detail_type", $result['detail_type']); // 2的时候不显示
        // 分支判断展示不同的待审批的内容画面
        switch ($result['detail_type']) {
            case 1:
                // 物料申购的申请内容
                $resultlist = Db::name("project_materiel")->alias("am")
                    ->field('ap.id as approval_id,pg.id as am_id,pg.*,g.goods_name,g.stock,g.price,g.price_unit,g.goods_num,r.room_name,u1.user_nickname apply_user')
                    ->leftJoin("project_materiel_goods pg", "pg.materiel_id=am.id")
                    ->leftJoin("goods g","g.id=pg.goods_id and g.type='1'")
                    ->leftJoin("room r","r.id=g.room")
                    ->leftJoin("user u1","am.apply_user=u1.id")
                    ->leftJoin("approval ap", "ap.form_id=am.id")
                    ->where('am.id', $result['form_id'])
                    //->where('ap.approval_status', "1")
                    ->where("ap.form_type","1")
                    ->where("ap.detail_type","1")
                    ->select();
//                var_dump(Db::name("project_materiel")->getLastSql());
                $this->assign("resultslist", $resultlist);
                $this->assign("approval_id", $resultlist[0]['approval_id']);

                break;
            case 2:
                // 发起项目
                $result = Db::name("project")->alias("a")->field('ap.id as approval_id,a.*,a.plan_time,u.user_nickname')
                    ->leftJoin("user u", "u.id=a.add_user")
                    ->leftJoin("approval ap", "ap.form_id=a.id")
                    ->leftJoin("user u1","ap.approval_user=u1.id")
                    ->where('a.id', $result['form_id'])
                    ->where("ap.form_type","3")
                    ->where("ap.detail_type","2")
                    ->find();
                $result['completion_time'] = date('Y/m/d',$result['completion_time']);
                $result['plan_time'] = date('Y/m/d',$result['plan_time']);
                $result['creat_time'] = date('Y/m/d H:i:s',$result['creat_time']);
                $this->assign($result);

                break;
            case 3:
                // 迁墓
                $this->getCommonInfo($result['form_id'],3);
                // 查询概况以外的其他内容
//                if($app_status == '1'){
//                    // 未审核的状态
//                    $deceased_list = Db::name('archives_deceased')->where("servicemove_id", $result['form_id'])
//                        ->where("move_status","1")->select();
//                    $this->assign('deceased_list',$deceased_list);
//                }else if($app_status == '2'){
//                    // 审核通过的状态
//                    $deceased_list = Db::name('archives_deceased')->where("servicemove_id", $result['form_id'])
//                        ->where("move_status","2")->select();
//                    $this->assign('deceased_list',$deceased_list);
//                }else{
                    // 已迁出
                    $deceased_list = Db::name('archives_deceased')->where("servicemove_id", $result['form_id'])->select();
                    $this->assign('deceased_list',$deceased_list);
//                }


                // 从服务管理的表中取数据
                $service = Db::name('service_move')->alias("s")
                    ->field("ap.id as approval_id,s.*,u.id,user_nickname,c.department_name")
                    ->leftJoin("user u","u.id=s.receptionist")
                    ->join('dj_department c','c.id=u.dept_id')
                    ->leftJoin("approval ap", "ap.form_id=s.id")
                    ->where(['u.user_type'=>2,'c.dept_type'=>4])
                    ->where(['s.id'=>$result['form_id']])
                    ->find();

                if(!empty($service)){
                    $service['move_time'] = date('Y-m-d H:i');
                    $this->assign("service",$service);
                }
                break;
            case 4:
                // 退墓
                $this->getCommonInfo($result['form_id'],4);
                // 从退墓表中取数据
                $tomb_list = Db::name('retreat_tomb')->alias("a")->field("a.*,ap.id as approval_id")
                    ->leftJoin("approval ap", "ap.form_id=a.id")
                    ->where("a.id", $result['form_id'])
                    ->where("ap.detail_type",4)
                    ->find();
                $this->assign('retreat',$tomb_list);
                // 退墓原因
                $refund_reason = [
                    '1'=>'产品外观原因',
                    '2'=>'产品质量原因',
                    '3'=>'环境服务原因',
                    '4'=>'客户原因',
                    '5'=>'竞争原因',
                    '6'=>'其他原因',
                ];
                $this->assign('refund_reason',$refund_reason);
                $this->assign("approval_id", $tomb_list['approval_id']);
                $this->assign('pay_type',cart_type('pay'));
                break;
            case 5:
                //证件变更
                $this->getCommonInfo($result['form_id'],5);
                // 从证件变更表中取数据
                $change_list = Db::name('change')->alias("p")
                    ->field("p.*,u.user_nickname,ap.id as approval_id")
                    ->leftJoin("approval ap", "ap.form_id=p.id")
                    ->join("dj_user u", "p.add_user=u.id", "left")
                    ->where("p.id", $result['form_id'])
                    ->where("ap.detail_type",5)
                    ->select()->toArray();
                $this->assign('change',$change_list[0]);
                $this->assign("approval_id", $change_list[0]['approval_id']);

                break;
            case 6:
                //证件挂失
                $this->getCommonInfo($result['form_id'],6);
                // 从证件变更表中取数据
                $change_list = Db::name('change')->alias("p")
                    ->field("p.*,u.user_nickname,ap.id as approval_id")
                    ->leftJoin("approval ap", "ap.form_id=p.id")
                    ->join("dj_user u", "p.add_user=u.id", "left")
                    ->where("p.id", $result['form_id'])
                    ->where("ap.detail_type",6)
                    ->select()->toArray();
                $this->assign('loss',$change_list[0]);
                $this->assign("approval_id", $change_list[0]['approval_id']);

                break;
            case 7:
                // 从服务管理的表中取数据
                $service = Db::name('service_deposit')->alias("s")
                    ->where(['s.id'=>$result['form_id'],'s.type'=>0])
                    //->where(['s.submit_status'=>2])
                    ->where("s.service_status", "neq",3)
                    ->find();
//                exit(json_encode($service));
                $deceased_list = Db::name('archives_deceased')->alias('ad')
                ->field('ad.*,od.deposit_time,od.id deposit_id')
                ->leftJoin('dj_order_deposit od','od.id = ad.deposit_id')
                ->where(['ad.tomb_id'=>$service['tomb_id'],'od.customer_id'=>$service['customer_id']])->select();
                $this->assign('service',$service);
                $this->assign('deceased_list',$deceased_list);
                $this->assign('user_nickname',$service['handle_name']);
                break;
            case 8 :
                // 从服务管理的表中取数据
                $service = Db::name('service_deposit')->alias("s")
                    ->where(['s.id'=>$result['form_id'],'s.type'=>1])
                    ->where("s.service_status", "neq","3")
                    ->find();
                $OrderModel = new OrderModel();
                $result_customer = $OrderModel->getOrderByCustomerId($service['customer_id']);
                $result_jc = Db::name('order_deposit')->where(['customer_id'=>$service['customer_id'],'status'=>1])->find();
                $service['customer_id'];


                $deceased_list = Db::name('archives_deceased')->alias('ad')
                    ->field('ad.*,od.deposit_time,od.id deposit_id')
                    ->leftJoin('dj_order_deposit od','od.id = ad.deposit_id')
                    ->where(['ad.tomb_id'=>$service['tomb_id'],'od.customer_id'=>$service['customer_id']])->select();


                $this->assign('result_jc',$result_jc);
                $this->assign('user_nickname',$service['handle_name']);
                $this->assign('deceased_list',$deceased_list);
                $this->assign('service',$service);
                $this->assign('result',$result_customer);
                break;
            case 9:
                $result_pay = PayDepositModel::where(['id'=>$result['form_id']])->find();

                $this->assign('result_pay',$result_pay);
                break;
        }
        return $this->fetch();
    }

    // 得到业务售后概况的信息
    public function getCommonInfo($form_id,$type){
        // 迁墓业务
        if($type == 3){
            $result1s = Db::name("archives_deceased")
                ->field('order_id')
                ->where("servicemove_id", $form_id)
                ->select();
            $order_id = $result1s[0]['order_id'];
        }elseif ($type==4){
            $result1s = Db::name("retreat_tomb")
                ->field('order_id')
                ->where("id", $form_id)
                ->select();
            $order_id = $result1s[0]['order_id'];
        }elseif ($type==5 || $type==6){
            $result1s = Db::name("change")
                ->field('order_id')
                ->where("id", $form_id)
                ->select();
            $order_id = $result1s[0]['order_id'];
        }elseif ($type==7){

        }
        $OrderModel = new OrderModel();
        $result = $OrderModel->getOrderByCustomerId($order_id,1);
//        $this->result_list =$result;

        $users = Db::name("user")->alias('u')->field('u.id,user_nickname,c.id dep_id,c.department_name')
            ->join('dj_department c','c.id=u.dept_id')->where(['u.user_type'=>2,'c.dept_type'=>4])->select();
        $dep = Db::name("department")->where(['dept_type'=>4])->select();
        $costset = Db::name('costset')->where(['id'=>1])->find()  ;

        foreach ($dep as $dk=>&$valued){
            $this->dep_list[$valued['id']]=$valued['department_name'];
        }
        foreach ($users as $dk=>&$valued){
            $this->users_array[$valued['id']]=$valued['user_nickname'];
        }
//        $this->tomb_num = $result['tomb_num'];
        $this->assign([
            'result'=>$result,
            'dep_list'=>$dep,
            'user_list'=>$users,
            'costset'=>$costset
        ]);

    }

    /*审批管理-去审批*/
    public function approvaladd_post()
    {
        $data = $this->request->param();
        // 添加数据
        $approval_status=$data['approval_status'];
        $approval_desc=$data['approval_desc'];
        if ($approval_status == '3' && empty($approval_desc)){
            $this->error("驳回时请填写意见描述");
        }

        $form_type = $data['form_type'];
        // 更新审批表的字段
        $approval_data['apply_time'] = strtotime($data['apply_time']);
        $approval_data['approval_time'] = time();
        $approval_data['approval_user'] = cmf_get_current_admin_id();
        $approval_data['approval_desc'] = $approval_desc;
        $approval_data['approval_status'] = $approval_status;
        $approval_data['form_type'] = $form_type;
//        $approval_data['id'] = $data['id'];


        Db::name("approval")->where(['id'=>$data['id']])->update($approval_data);

        $detail_type = $data['detail_type'];
        $form_id = $data['form_id'];

        if($form_type == '1' && $detail_type == '1' && $approval_status == '2'){
            // 物料申购审批通过去更新goods表的库存
            $resultlist = Db::name("project_materiel_goods")->alias("mg")
                ->field('mg.*')
                ->leftJoin("project_materiel pm", "mg.materiel_id=pm.id")
                ->where('mg.materiel_id', $form_id)
                ->select();
            if(!empty($resultlist)){
                foreach ($resultlist as $re) {
                    $goods_id = $re['goods_id'];
                    $result = Db::name("goods")->where("id",$goods_id)->find();

                    if(!empty($result)){
                        $stock1 = $result['stock'];
                        $stock2 = $re['num'];
                        $stock3 = $stock1 + $stock2;
                        $result['stock'] = $stock3;
                        Db::name("goods")->update($result);

                        // 保存一条入库记录
                        $data = [];
                        $data['goods_id'] = $goods_id;
                        $data['type'] = 1;
                        $data['from'] = 'add';
                        $data['num'] = $stock2;
                        $data['add_user'] = cmf_get_current_admin_id();
                        $data['add_time'] = time();
                        $this->log_model->insert($data);
                    }
                }
            }
        }
        // 迁墓审核 同意的时候更新几张表
        if($form_type == '2' && $detail_type == '3' && $approval_status == '2'){

            $tomb_id = $data['tomb_id'];
            // 根据form_id 去查询service_move表内容
            $servicemove =  Db::name("service_move")->alias("sm")
                ->field('sm.tomb_num,sm.receptionist,sm.customer_id,sm.order_id,c.buyer_name,c.buyer_phone')
                ->join("dj_customer_info c","sm.customer_id = c.id")
                ->where("sm.id",$form_id)->find();

            $ContractModel = new ContractModel();
            $contract_sn = ContractModel::get_qm_contract_sn();
            $file = $ContractModel->content_temp_quanmu($form_id,$servicemove['order_id'],$contract_sn);
            ServiceMoveModel::update(['submit_status'=>3,'contract_sn'=>$contract_sn,'contract_file'=>json_encode($file)],['id'=>$form_id]);

            // 逝者信息表的迁出状态改为已审核通过，用于页面判断用
            ArchivesDeceasedModel::update(['move_status'=>2],["servicemove_id"=>$form_id]);

            // 迁墓后要更改墓位状态为迁墓中
            $tomb['col_status'] = '8';
            TombareaRowColModel::update($tomb,["colID"=>$tomb_id]);

            // 插入财务表
            $pay_ins = [
                'type'=>3,
                'itype'=>8,
                'order_id'=>$this->result_list['order_id'],
                'pay_sn'=>OrderPayLogModel::getselfPayNum('add_time','pay_sn','JS-'),
                'tomb_id'=>$tomb_id,
                'tomb_num'=>$servicemove['tomb_num'],
                'real_name'=>$servicemove['buyer_name'],//
                'real_phone'=>$servicemove['buyer_phone'],//
                'tom_price'=>0,//购墓价格
                'discount_rate'=>0,//折扣
                'deal_price'=>$data['move_money'],//成交
                'total_price'=>$data['move_money'],//应收金额
                'add_time'=>time(),//备注
                'handle'=>$servicemove['receptionist'],//收款人
                'pay_real_name'=>cmf_get_current_admin_id(),//收款人
                'status'=> 0,// 付款方式
                'other_id'=> $form_id,
                'customer_id' => $servicemove['customer_id'],
            ];

             Db::name('order_pay_log')->insertGetId($pay_ins);

        }else if($form_type == '2' && $detail_type == '3' && $approval_status == '3'){
            // 迁墓驳回的时候
            ServiceMoveModel::update(['submit_status'=>4],["id"=>$form_id]);
        }else if($form_type == '2' && $detail_type == '4' && $approval_status == '2'){
            // 退墓审核 同意修改 PayRefundModel 退金额
            PayRefundModel::update(['refund_apply_state'=>2],['other_id'=>$form_id,'type'=>2]);
//        // 退墓审核 同意的时候更新dj_tombarea_row_col状态为空闲
//            // 根据form_id 去查询dj_retreat_tomb表内容
//            $tomb =  Db::name("tombarea_row_col")->alias("c")
//                ->field('c.*')
//                ->leftJoin("retreat_tomb t", "t.mw_id=c.colID")->where("t.id",$form_id)->find();
//            $tomb['col_status'] = '1';
//            Db::name("tombarea_row_col")->update($tomb);

        }else if($form_type == '2' && $detail_type == 8 && $approval_status == 2){
            // 寄存寄出  -- 审核同意 更新类型为寄出，审核通过
            ServiceDepositModel::update(['submit_status'=>3,'type'=>1],["id"=>$form_id]);
            // 寄出状态改为已审核通过，用于页面判断用
            ArchivesDeceasedModel::update(['deposit_status'=>2],["servicedeposit_id"=>$form_id]);

        }else if($form_type == '2' && $detail_type == 8 && $approval_status == 3){
            // 寄存寄出  -- 审核驳回
            ServiceDepositModel::update(['submit_status'=>4],["id"=>$form_id]);

        }else if($form_type == '2' && $detail_type == 5 && $approval_status == 2){
            // 证件变更  -- 审核同意
            //  获取新证件人信息
            $change =  Db::name("change")->alias("c")
                ->field('c.*')
                ->leftJoin("customer_info i", "i.id=c.customer_id")->where("c.id",$form_id)->find();
            $change['status'] = '2';
            Db::name("change")->where(['id'=>$change['id']])->update($change);
            //  去购墓人信息表 修改购墓人证件信息
            $customer_info['customer_account'] = $change['cart_ID'];
            $customer_info['buyer_name'] = $change['name'];
            $customer_info['buyer_sex'] = $change['sex'];
            $customer_info['buyer_phone'] = $change['phone'];
            $customer_info['cart_ID'] = $change['cart_ID'];
            $customer_info['cart_upload'] = $change['cart_upload'];
            $customer_info['cart_upload_id'] = $change['cart_upload_id'];
            $customer_info['customer_address'] = $change['customer_address'];

            Db::name("customer_info")->where(['id'=>$change['customer_id']])->update($customer_info);

        }else if($form_type == '2' && $detail_type == 6 && $approval_status == 2){
            // 证件挂失  -- 审核同意
            //  修改审核状态
            $change =  Db::name("change")->alias("c")
                ->field('c.*')
                ->leftJoin("customer_info i", "i.id=c.customer_id")->where("c.id",$form_id)->find();
            ChangeModel::update(['status'=>2],['id'=>$change['id']]);
            // 往财务表插数据
            $pay_ins = [
                'type'=>3,//售后
                'itype'=>7,//挂失工本费
                'pay_sn'=>OrderPayLogModel::getselfPayNum('add_time','pay_sn','JS-'),//'JS'.date('YmdHi'),
                'order_id'=>$change['order_id'],
                'other_id'=>$form_id,
                'tomb_id'=>$change['tomb_id'],
                'handle'=>$change['add_user'],//收款人
                'tomb_num'=>$data['tomb_num'],
                'total_price'=>$change['cost'],//应收金额
                'add_time'=>time(),//备注
                'status'=> 0,// 付款方式
                'real_name'=>$change['name'],//新证件姓名
                'real_phone'=>$change['phone'],//新证件联系方式
                'customer_id'=>$change['customer_id'],
            ];
            Db::name('order_pay_log')->insertGetId($pay_ins);

        }else if($form_type == '2' && ($detail_type == 5 || $detail_type == 6) && $approval_status == 3){
            // 证件变更  -- 审核驳回
            $change =  Db::name("change")->alias("c")
                ->field('c.*')
                ->leftJoin("customer_info i", "i.id=c.customer_id")->where("c.id",$form_id)->find();
            $change['status'] = '3';
            Db::name("change")->where(['id'=>$change['id']])->update($change);


        }

        $this->success("审批成功", url('Office/approval'));
    }
}